﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace dataSendModel.Util
{
    /// <summary>
    /// 同步Socket客户端类
    /// </summary>
    public class SynchronousClient
    {
        private string ip;
        private string port;
        private Socket socket;

        public string Ip
        {
            get { return ip; }
            set { ip = value; }
        }

        public string Port
        {
            get { return port; }
            set { port = value; }
        }

        /// <summary>
        /// 同步Socket客户端构造函数
        /// </summary>
        /// <param name="ip">服务器IP地址</param>
        /// <param name="port">服务器端口</param>
        public SynchronousClient(string ip, string port)
        {
            this.ip = ip;
            this.port = port;
        }

        /// <summary>
        /// 开始连接
        /// </summary>
        public void Start()
        {
            IPAddress ipAddress = IPAddress.Parse(Ip);
            IPEndPoint ipe = new IPEndPoint(ipAddress, Int32.Parse(Port));

            // 创建Socket实例
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(ipe);

            if (socket.Connected)
                this.socket = socket;
        }

        /// <summary>
        ///  向GPS服务器发送字节数组
        /// </summary>
        /// <param name="sendData">发送字节数组</param>
        public void Send(byte[] sendData)
        {
            if (this.socket.Connected)
            {
                this.socket.Send(sendData);
            }
        }

        /// <summary>
        /// 接收从GPS服务器响应的字节数组
        /// </summary>
        /// <param name="receiveData">接收字节数组</param>
        public int Receive(byte[] receiveData)
        {
            //if (this.socket.Connected)
            //{
            //    this.socket.Receive(receiveData);
            //}
            return this.socket.Receive(receiveData);
        }

        /// <summary>
        /// 结束连接
        /// </summary>
        public void Close()
        {
            if (socket.Connected)
                this.socket.Close();
        }
    }
}
